import 'package:cdd_f_1/calculator/history.dart';
import 'package:flutter/material.dart';
import 'package:string_num_calculate/string_num_calculate.dart';

import 'Store.dart';

class CalculatorHome extends StatefulWidget {
  CalculatorHome({Key key}) : super(key: key);

  final Map<String, String> _char = {
    '+': '+',
    '-': '-',
    '×': '×',
    '÷': '÷',
    '%': '%',
  };

  @override
  _CalculatorHomeState createState() => _CalculatorHomeState();
}

class _CalculatorHomeState extends State<CalculatorHome> {
  String inputStr = '', result = '';
  List<InputStr> history = [];

  ///算术计算
  String calc(String string) {
    return Calculate.LinierCalculate(string).toString();
  }

  ///处理计算
  dynamic handleTap(String char) {
    List l1 = ['+', '-', '×', '÷', '%', '/', '*'],
        l2 = [
          '1',
          '2',
          '3',
          '4',
          '5',
          '6',
          '7',
          '8',
          '9',
          '0',
        ];
    //平常数字处理
    if (l2.indexOf(char) >= 0) {
      return setState(() {
        if (result != null || result != '') result = '';
        inputStr = Calculate.formatList(
                Calculate.toNumberList(inputStr + char, onlyNumber: false))
            .join('');
      });
    }

    // 末尾符号处理
    if (l1.contains(char)) {
      if (!l1.contains(inputStr[inputStr.length - 1])) {
        setState(() {
          inputStr += char;
        });
      } else {
        setState(() {
          int len = inputStr.length;
          inputStr = inputStr.replaceRange(len - 1, len, char);
        });
      }
    }
    //其他符号处理
    switch (char) {
      case '.':
        if (inputStr == '' || inputStr == null) {
          setState(() {
            inputStr = '.';
          });
        } else {
          var list = inputStr.split(RegExp(r'[*+\-×÷%]'));
          if (list.last != null && list.last.contains('.')) {
            return;
          } else {
            setState(() {
              inputStr += char;
            });
          }
        }

        break;
      case '=':
        setState(() {
          result = calc(inputStr);
          history.addAll([
            InputStr(text: inputStr, type: inputType.expression),
            InputStr(text: result, type: inputType.result),
          ]);
          inputStr = '';
        });
        break;
      case 'AC':
        setState(() {
          if (inputStr != null || inputStr != '') {
            inputStr = inputStr.substring(0, inputStr.length - 1);
          }
        });
        break;
    }
  }

  ///获取slice
  Widget getSlice(
      {Widget child,
      String char,
      @required String calcChar,
      flex = 1,
      onTap,
      Color color,
      @required BuildContext context,
      langPress}) {
    Widget _child;
    if (child != null)
      _child = child;
    else
      _child = Text(
        char,
        style: TextStyle(fontSize: 35),
      );
    return Expanded(
      flex: flex,
      child: Container(
        padding: EdgeInsets.all(6.18),
        height: double.infinity,
        // color: Theme.of(context).primaryColor.withAlpha(80),
        child: RaisedButton(
          onLongPress: () {
            if (langPress != null) {
              langPress(calcChar);
            }
          },
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
          color: color != null ? color : Theme.of(context).primaryColor,
          onPressed: () {
            if (onTap != null) {
              onTap(calcChar);
            }
          },
          child: _child,
        ),
      ),
    );
  }

  ///获取line
  Widget getLine(List<Widget> child) {
    return Expanded(
      child: Container(
        height: double.infinity,
        child: Row(
          children: child,
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext _) {
    Size size = MediaQuery.of(_).size;

    // 第一行
    Widget line1 = getLine(
      [
        getSlice(
            context: _,
            char: 'AC',
            calcChar: 'AC',
            onTap: handleTap,
            flex: 2,
            langPress: (char) {
              setState(() {
                inputStr = result = '';
              });
            }),
        getSlice(context: _, char: '%', calcChar: '%', onTap: handleTap),
        getSlice(context: _, char: '÷', calcChar: '÷', onTap: handleTap),
      ],
    );
    Widget line2 = getLine([
      getSlice(calcChar: '7', char: '7', context: _, onTap: handleTap),
      getSlice(calcChar: '8', char: '8', context: _, onTap: handleTap),
      getSlice(calcChar: '9', char: '9', context: _, onTap: handleTap),
      getSlice(calcChar: '×', char: '×', context: _, onTap: handleTap),
    ]);
    Widget line3 = getLine([
      getSlice(calcChar: '4', char: '4', context: _, onTap: handleTap),
      getSlice(calcChar: '5', char: '5', context: _, onTap: handleTap),
      getSlice(calcChar: '6', char: '6', context: _, onTap: handleTap),
      getSlice(calcChar: '-', char: '-', context: _, onTap: handleTap),
    ]);
    Widget line4 = getLine([
      getSlice(calcChar: '1', char: '1', context: _, onTap: handleTap),
      getSlice(calcChar: '2', char: '2', context: _, onTap: handleTap),
      getSlice(calcChar: '3', char: '3', context: _, onTap: handleTap),
      getSlice(calcChar: '+', char: '+', context: _, onTap: handleTap),
    ]);
    Widget line5 = getLine([
      getSlice(calcChar: '0', char: '0', context: _, onTap: handleTap),
      getSlice(calcChar: '.', char: '.', context: _, onTap: handleTap),
      getSlice(calcChar: '=', char: '=', context: _, onTap: handleTap, flex: 2),
    ]);

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(_).primaryColor,
        toolbarHeight: 50,
        leading: Container(
          padding: EdgeInsets.only(left: 10),
          child: Center(
            child: Text('计算器'),
          ),
        ),
        actions: [
          IconButton(
              icon: Icon(Icons.history),
              onPressed: () {
                Navigator.push(_, MaterialPageRoute(builder: (_) {
                  return History();
                }));
              }),
        ],
      ),
      body: Container(
        width: double.infinity,
        height: double.infinity,
        child: Column(
          children: [
            // 显示部分
            Expanded(
              child: Container(
                  height: double.infinity,
                  width: double.infinity,
                  padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
                  color: Colors.black12,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Expanded(
                        // height: 160,
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 15),
                          child: ListView.builder(
                            physics: BouncingScrollPhysics(),
                            itemCount: history.length,
                            itemBuilder: (BuildContext context, int index) {
                              return ListTile(
                                trailing: Text(
                                  history[index].text,
                                  style: TextStyle(fontSize: 18),
                                ),
                              );
                            },
                          ),
                        ),
                      ),
                      Container(
                        constraints:
                            BoxConstraints(minHeight: 100, maxHeight: 150),
                        child: Column(
                          children: [
                            SizedBox(
                              height: 60,
                              child: Text(
                                result != null ? result : '',
                                style: TextStyle(fontSize: 60),
                              ),
                            ),
                            Expanded(
                              child: Text(
                                inputStr,
                                style: TextStyle(fontSize: 40),
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  )),
            ),
            //计算器部分
            Container(
              height: size.height * .518,
              constraints: BoxConstraints(maxHeight: 380),
              width: double.infinity,
              decoration: BoxDecoration(
                color: Colors.blueGrey[100],
                boxShadow: [
                  BoxShadow(
                    color: Theme.of(_).primaryColor,
                    offset: Offset(0, 2),
                    blurRadius: 10,
                  )
                ],
              ),
              child: Column(
                children: [line1, line2, line3, line4, line5],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
